﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint;

namespace Inline.SharePoint.ExtendedVariations.Helpers
{

    public class Logger
    {

        private const string _logListName = "Inline.SharePoint.ExtendedVariations.Logs";
        public enum LogLevel { Error, Informative }

        private VariationHandler _variationHandler = new VariationHandler();

        public void WriteEntry(string currentWebUrl, string source, string message, LogLevel logLevel)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                PublishingWeb rootVariation = _variationHandler.GetVariationRootPublishingWeb(currentWebUrl);
                VariationLabel sourceVariationLabel = _variationHandler.GetSourceVariationLabel(currentWebUrl);

                if (rootVariation != null)
                {

                    using (SPSite site = new SPSite(sourceVariationLabel.TopWebUrl))
                    {

                        using (SPWeb web = site.OpenWeb())
                        {

                            SPList list = web.Lists.TryGetList(_logListName);

                            if (list != null)
                            {

                                SPListItem item = list.Items.Add();
                                item[SPBuiltInFieldId.Title] = source;
                                item["Message"] = message;

                                if (logLevel == LogLevel.Error)
                                    item["LogLevel"] = "Error";
                                else if (logLevel == LogLevel.Informative)
                                    item["LogLevel"] = "Informative";

                                web.AllowUnsafeUpdates = true;
                                item.Update();
                                web.AllowUnsafeUpdates = false;

                            }

                        }

                    }

                }

            });

        }

    }

}
